<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\common\exception\UploadException;
use app\common\library\Upload;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use think\Db;

class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function index()
    {
        return $this->view->fetch();
    }

    public function check_es()
    {
        $list = Db::table('check_key')
                        ->group('key')
                        ->order('id desc')
                        ->paginate(10);
        $page = $list->render();
        // 模板变量赋值
        $this->assign('list', $list);
        $this->assign('page', $page);
        return $this->fetch();
    }
    
    public function check()
    {
        set_time_limit(0);
        $attachment = null;
        //默认普通上传文件
        $file = $this->request->file('file');
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload();
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        }
        $res = [];
        if(is_file('.'.$attachment->url)){
            Db::table('check_key')->where('1=1')->delete();
            $res = self::import('.'.$attachment->url);
            $this->success('导入成功,请等待任务执行','/index.php/index/index/check_es');
            // $this->assign('data',$res);
        }
    }

        /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function import($file)
    {
        set_time_limit(0);
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //加载文件
        $insert = [];
        $new_insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    // var_dump($k);
                    // $row[$k*2-1] = $v;
                    // $row[$k*2] = self::http_curl_get($v);
                    if($v){
                        $new_insert[] = ['key'=>$v,'status'=>'','title'=>$k];
                    }
                }
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            // $this->error(__('No rows were updated'));
        }
        // var_dump($new_insert);die;
        Db::table('check_key')->insertAll($new_insert);
        
        // var_dump($new_insert);die;
        // return $insert;
        // self::export($insert);
    }
    public function check_out()
    {
        $list = Db::table('check_key')->field('title,key,status')
        ->group('key')
        ->order('id desc')
        ->select();
        if($list){
            self::export($list);
        }else{
            $this->error('没有数据');
        }
    }
    public function export($list)
    {
    $first = array_keys($list[0]);
    set_time_limit(0);
    $excel = new Spreadsheet();
    $excel->getProperties()
    ->setCreator("FastAdmin")
    ->setLastModifiedBy("FastAdmin")
    ->setTitle("标题")
    ->setSubject("Subject");
    $excel->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
    $excel->getDefaultStyle()->getFont()->setSize(12);
            $excel->getDefaultStyle()->applyFromArray(
                array(
                    'fill'      => array(
                        'type'  => Fill::FILL_SOLID,
                        'color' => array('rgb' => '000000')
                    ),
                    'font'      => array(
                        'color' => array('rgb' => "000000"),
                    ),
                    'alignment' => array(
                        'vertical'   => Alignment::VERTICAL_CENTER,
                        'horizontal' => Alignment::HORIZONTAL_CENTER,
                        'indent'     => 1
                    ),
                    'borders'   => array(
                        'allborders' => array('style' => Border::BORDER_THIN),
                    )
                ));
            
            $worksheet = $excel->setActiveSheetIndex(0);
            $worksheet->setTitle('秘钥检查');
            $line = 1;
            $styleArray = array(
                'font' => array(
                    'color' => array('rgb' => '000000'),
                    'size'  => 12,
                    'name'  => 'Verdana'
                ));
            $items = $list;
            foreach ($items as $index => $item) {
                $line++;
                $col = 1;
                foreach ($item as $field => $value) {
                    $worksheet->setCellValueByColumnAndRow($col, $line, $value);
                    $worksheet->getStyleByColumnAndRow($col, $line)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                    $worksheet->getCellByColumnAndRow($col, $line)->getStyle()->applyFromArray($styleArray);
                    $col++;
                }
            }
            // foreach ($first as $index => $item) {
            //     $worksheet->setCellValueByColumnAndRow($index+1, 1, $item);
            // }
            $excel->createSheet();
            $title = date("YmdHis");
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
            header('Cache-Control: max-age=0');
            // If you're serving to IE 9, then the following may be needed
            header('Cache-Control: max-age=1');
            // If you're serving to IE over SSL, then the following may be needed
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0
            $objWriter = IOFactory::createWriter($excel, 'Xlsx');
            $objWriter->save('php://output');
            return;
    }

    function http_curl_get($code) {
        $type=1;
        $url='https://autochess.ppbizon.com/cdkey/get/@';
        $curl = curl_init();
        curl_setopt($curl,CURLOPT_TIMEOUT,5000);
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($curl,CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl,CURLOPT_URL,$url.$code);
        if($type == 1){
            curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
        }
        $res = curl_exec($curl);
        if($res){
            curl_close($curl);
            $str = $res;
            // var_dump($res);
            // var_dump(mb_strpos($str, '已被激活'));
            return mb_strpos($str, '已被激活') ? '已被激活':'未激活';
        }else {
            $error = curl_errno($curl);
            curl_close($curl);
            return $error;
        }
    }
}
